﻿#include "stdafx.h"
#include "Chat.h"
#include <QTextDocument>

Chat::Chat(QWidget *parent)
	: QWidget(parent)
{
	ui.setupUi(this);
    setAttribute(Qt::WA_TranslucentBackground, true);
    //setAttribute(Qt::WA_NoSystemBackground, true);
	
#ifdef Q_OS_WIN32
    // 去掉窗口标题栏方式
    setWindowFlags(Qt::FramelessWindowHint | Qt::WindowMinimizeButtonHint | Qt::WindowMaximizeButtonHint | Qt::WindowCloseButtonHint);
    ui.maximizeSysButton->setProperty("windowMaxsized", false);
    setProperty("isWin32", true);
    ui.verticalLayout->setContentsMargins(6, 6, 6, 6);
#else
    ui.minisizeSysButton->hide();
    ui.maximizeSysButton->hide();
    ui.closeSysButton->hide();
    setProperty("isWin32", false);
#endif

    ui.portraitLabel->setScaledContents(true);

	QApplication::alert(this, 2000);			// FlashWindow
    {
        // 此括号内为测试数据
        setUserPortrait();


        ui.nicknameLabel->setFixedWidth(150);
        ui.nicknameLabel->setText("<b>ˊ謎亂﹏dddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddd丶</b>");

        ui.signatureEdit->setText("个性签名是从腾讯qq聊天软件延伸出来的一个功能dddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddaav");
        ui.signatureEdit->home(false);


        ui.textEdit->setMinimumHeight(80);
        ui.splitter->setHandleWidth(1);
        ui.sendButton->setFocusProxy(ui.textEdit);
    }
}

Chat::~Chat()
{

}

void Chat::paintEvent(QPaintEvent* /*event*/)
{
    QStyleOption opt;
    opt.init(this);
    QPainter p(this);
    p.setRenderHint(QPainter::Antialiasing);

#ifdef Q_OS_WIN32
    if (!IsZoomed((HWND)this->effectiveWinId()))
    {
        p.fillRect(this->rect().left()+6, this->rect().top()+6, this->rect().width()-12, this->rect().height()-12, QColor(232, 236, 247));
        style()->drawPrimitive(QStyle::PE_Widget, &opt, &p, this);
    }
    else
#endif
    {
        p.fillRect(this->rect(), QColor(232, 236, 247));
    }

//    //绘制圆角矩形
//    QPainter painter(this);
//    painter.setRenderHint(QPainter::Antialiasing);
//    // 绘制背景图片
//    //painter.fillRect(QRect(this->rect().left()+6, this->rect().top()+6, this->rect().width()-12, this->rect().height()-12), QColor(232,236,247));
//#ifdef Q_OS_WIN32
//    if (!this->isFullScreen() && !this->isMaximized())
//    {
//        int nImgWidth = 43;
//        int nImgHeight = 40;
//        int nBorder = 8;

//        // TOPLEFT
//        painter.drawImage(QRect(0, 0, nBorder, nBorder), QImage(":/Frame/widget_border"), QRect(0, 0, nBorder, nBorder));
//        // LEFT
//        painter.drawImage(QRect(0, nBorder, nBorder, this->height()-nBorder*2), QImage(":/Frame/widget_border"), QRect(0, nBorder, nBorder, nImgHeight-nBorder*2));
//        // BOTTOMLEFT
//        painter.drawImage(QRect(0, this->height()-nBorder, nBorder, nBorder), QImage(":/Frame/widget_border"), QRect(0, nImgHeight-nBorder, nBorder, nBorder));
//        // BOTTOM
//        painter.drawImage(QRect(nBorder, this->height()-nBorder, this->width()-nBorder*2, nBorder), QImage(":/Frame/widget_border"), QRect(nBorder, nImgHeight-nBorder, nImgWidth-nBorder*2, nBorder));
//        // BOTTOMRIGHT
//        painter.drawImage(QRect(this->width()-nBorder, this->height()-nBorder, nBorder, nBorder), QImage(":/Frame/widget_border"), QRect(nImgWidth-nBorder, nImgHeight-nBorder, nBorder, nBorder));
//        // RIGHT
//        painter.drawImage(QRect(this->width()-nBorder, nBorder, nBorder, this->height()-nBorder*2), QImage(":/Frame/widget_border"), QRect(nImgWidth-nBorder, nBorder, nBorder, nImgHeight-nBorder*2));
//        // TOPRIGHT
//        painter.drawImage(QRect(this->width()-nBorder, 0, nBorder, nBorder), QImage(":/Frame/widget_border"), QRect(nImgWidth-nBorder, 0, nBorder, nBorder));
//        // TOP
//        painter.drawImage(QRect(nBorder, 0, this->width()-nBorder*2, nBorder), QImage(":/Frame/widget_border"), QRect(nBorder, 0, nImgHeight-nBorder*2, nBorder));
//    }
//#endif
}

#ifdef Q_OS_WIN32
void Chat::changeEvent(QEvent* event)
{
	if (event->type() == QEvent::WindowStateChange)
	{
		//QWindowStateChangeEvent* e = static_cast<QWindowStateChangeEvent*>(event);
		if (isMinimized())
		{
			// MINIMIZED
		}
		else if (isMaximized())
		{
			// MAXIMIZED
            ui.maximizeSysButton->setProperty("windowMaxsized", true);
            ui.maximizeSysButton->style()->polish(ui.maximizeSysButton);
            ui.maximizeSysButton->update();
            ui.verticalLayout->setContentsMargins(0, 0, 0, 0);
		}
		else
		{
			// Restore
            ui.maximizeSysButton->setProperty("windowMaxsized", false);
            ui.maximizeSysButton->style()->polish(ui.maximizeSysButton);
            ui.maximizeSysButton->update();
            ui.verticalLayout->setContentsMargins(6, 6, 6, 6);
		}
	}

    QWidget::changeEvent(event);
}

bool Chat::nativeEvent(const QByteArray &eventType, void *message, long *result)
{
    if (eventType == "windows_generic_MSG")
    {
        MSG* msg = (MSG*)message;
        switch(msg->message)
        {
        case WM_NCHITTEST:
            {
                if (!this->isMaximized() && !this->isFullScreen())
                {
                    int xPos = GET_X_LPARAM(msg->lParam) - this->frameGeometry().x();
                    int yPos = GET_Y_LPARAM(msg->lParam) - this->frameGeometry().y();
                    int nBorderWidth = 8;
                    int nBorderRadius = 8;
                    QWidget* widget = this->childAt(xPos, yPos);
                    if (xPos < nBorderRadius && yPos < nBorderRadius)
                    {
                        *result = HTTOPLEFT;
                    }
                    else if (xPos < nBorderRadius && yPos > this->height() - nBorderRadius)
                    {
                        *result = HTBOTTOMLEFT;
                    }
                    else if (xPos > this->width() - nBorderRadius && yPos < nBorderRadius)
                    {
                        *result = HTTOPRIGHT;
                    }
                    else if (xPos > this->width() - nBorderRadius && yPos > this->height() - nBorderRadius)
                    {
                        *result = HTBOTTOMRIGHT;
                    }
                    else if (xPos < nBorderWidth)
                    {
                        *result = HTLEFT;
                    }
                    else if (yPos < nBorderWidth)
                    {
                        *result = HTTOP;
                    }
                    else if (yPos > this->height() - nBorderWidth)
                    {
                        *result = HTBOTTOM;
                    }
                    else if (xPos > this->width() - nBorderWidth)
                    {
                        *result = HTRIGHT;
                    }
                    else if (widget == nullptr)
                    {
                        *result = HTCAPTION;
                    }
                    //else if (widget->objectName() == "nicknameLabel")
                    //{
                    //    *result = HTCAPTION;
                    //}
                    else
                    {
                        return false;
                    }

                    return true;
                }
                else
                {
                    int xPos = GET_X_LPARAM(msg->lParam) - this->frameGeometry().x();
                    int yPos = GET_Y_LPARAM(msg->lParam) - this->frameGeometry().y();
                    QWidget* widget = this->childAt(xPos, yPos);
                    if (widget == nullptr)
                        *result = HTCAPTION;
                    //else if (widget->objectName() == "nicknameLabel")
                    //    *result = HTCAPTION;
                    else
                        return false;

                    return true;
                }
            }
            break;

        case WM_GETMINMAXINFO:
            {
                MINMAXINFO *lpMMI = (MINMAXINFO*)msg->lParam;
                QDesktopWidget desktopWidget;
                QRect desktop = desktopWidget.availableGeometry();
                lpMMI->ptMaxSize.x = desktop.width();
                lpMMI->ptMaxSize.y = desktop.height();
                lpMMI->ptMaxPosition.x = desktop.x();
                lpMMI->ptMaxPosition.y = desktop.y();
                lpMMI->ptMinTrackSize.x = 567; // minimum width for your window
                lpMMI->ptMinTrackSize.y = 463; // minimum height for your window
                lpMMI->ptMaxTrackSize.x = desktop.width();
                lpMMI->ptMaxTrackSize.y = desktop.height();

                result = 0;
                return true;
            }
            break;
        }
    }

    return false;
}
#endif

#ifdef Q_OS_WIN32
void Chat::on_minisizeSysButton_clicked()
{
    this->showMinimized();
}

void Chat::on_maximizeSysButton_clicked()
{
    if (isMaximized())
    {
        // Restore
        this->showNormal();
    }
    else
    {
        // Maxsize
        this->showMaximized();
    }
}

void Chat::on_closeSysButton_clicked()
{
    this->close();
}
#endif

void Chat::on_signatureEdit_editingFinished()
{
    ui.signatureEdit->home(false);
}

void Chat::on_fontQuickButton_clicked()
{
    bool ok;
    QFont font = QFontDialog::getFont(&ok, ui.textEdit->font(), this);
    if (ok)
    {
        // the user clicked OK and font is set to the font the user selected
        ui.textEdit->setFont(font);
    }
    else
    {
        // the user canceled the dialog; font is set to the initial
        // value, in this case Helvetica [Cronyx], 10
    }
}

void Chat::on_faceQuickButton_clicked()
{
    QString file = QFileDialog::getOpenFileName(this, tr("Select an image选则一个图片"),
                                                QStandardPaths::writableLocation(QStandardPaths::DesktopLocation),
                                                tr("Image Files (*.png *.jpg *.bmp *.gif)"));
    if (!file.isEmpty())
    {
        //QImage image = QImageReader(file).read();
        QImage image(file);
        if (!image.isNull())
        {
            //QTextDocument * textDocument = ui.textEdit->document();
            //textDocument->addResource( QTextDocument::ImageResource, Uri, QVariant ( image ) );
            //QTextImageFormat imageFormat;
            //imageFormat.setWidth( image.width() );
            //imageFormat.setHeight( image.height() );
            //imageFormat.setName( Uri.toString() );
            QTextCursor cursor = ui.textEdit->textCursor();
            cursor.insertImage(image, file);
        }
    }
}

void Chat::on_closeButton_clicked()
{
    //this->close();
    //QString str = QString("<img src=\"C:/Users/Administrator/Desktop/1111a.gif\"/>");
   // ui.textEdit->insertHtml(str);

    QTextDocumentFragment fragment;
    fragment = QTextDocumentFragment::fromHtml("<img src='C:/Users/Administrator/Desktop/1111.gif'>");
    ui.textEdit->textCursor().insertFragment(fragment);
}

void Chat::on_sendButton_clicked()
{
    QString str = ui.textEdit->toHtml();

    //str = ui.textEdit->placeholderText();
 //    QString str = ui.textEdit->toPlainText();
//    if (!str.isEmpty())
//    {
//        ui.textEdit->clear();
//        ui.textBrowser->append(str);
//    }
    //ui.textEdit->setFocus();
    qDebug() << str;
    //ui.textBrowser->append(str);


    QTextDocument *document = ui.textEdit->document();
    if (document->isEmpty())
        return;
    for (QTextBlock currentBlock = document->begin(); currentBlock != document->end(); currentBlock = currentBlock.next())
    {
        //QString str = it.text();
        //qDebug() << it.text();
        //QTextFragment currentFragment = it.fragment();
      //  QTextImageFormat newImageFormat = currentFragment.charFormat().toImageFormat();
       // qDebug() << it;
            //cout << it.text().toStdString() << endl;
        QTextBlock::iterator it;
        for (it = currentBlock.begin(); !(it.atEnd()); it++)
        {
           QTextFragment currentFragment = it.fragment();
           QTextCharFormat textCharFormat = currentFragment.charFormat();
           qDebug() << textCharFormat.objectType() << textCharFormat.type();

           if (textCharFormat.objectType() == QTextFormat::ImageObject)
           {
               QTextImageFormat imageFormat = textCharFormat.toImageFormat();
               if (imageFormat.isValid())
               {
                   qDebug() << imageFormat.name() << currentFragment.text();

                   QTextCursor prev_cursor = ui.textBrowser->textCursor();
                   ui.textBrowser->moveCursor(QTextCursor::End);

                   ui.textBrowser->textCursor().insertImage(imageFormat.name());
                  // ui.textBrowser->textCursor().insertText(currentFragment.text(), format);
                   ui.textBrowser->setTextCursor(prev_cursor);
               }
           }
           else if (textCharFormat.objectType() == QTextFormat::NoObject)
           {
              // QString strText = textCharFormat.anchorHref();
               //qDebug() << textCharFormat.anchorHref() << textCharFormat.toolTip() << currentFragment.text();
               //QTextImageFormat imageFormat = textCharFormat.toCharFormat();
               //QString strText = QString("<body style=\" font-family:'%1'; font-size:%2pt; font-weight:%3; font-style:%4;\"><p>%5</p></body>")
              //         .arg(textCharFormat.font().family()).arg(textCharFormat.font().pointSize()).arg(textCharFormat.font().weight()).arg("italic").arg(currentFragment.text());


              // int  ddd = textCharFormat.fontStretch();
               //qreal ddd1 = textCharFormat.font().pointSize();
               //qDebug() << textCharFormat.font().styleName() << textCharFormat.font;
              // <body style=" font-family:'宋体'; font-size:11pt; font-weight:400; font-style:italic;"><p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;">6ttt</p></body>
             // QString str = textCharFormat.font().toString();
              // ui.textBrowser->setCurrentFont(textCharFormat.font());

               QFont font(textCharFormat.font().family(), textCharFormat.font().pointSize(), textCharFormat.font().weight(), textCharFormat.font().italic());
               font.setStrikeOut(textCharFormat.font().strikeOut());
               font.setUnderline(textCharFormat.font().underline());
               //QColor textColor(textCharFormat.foreground().color().red(), textCharFormat.foreground().color().green(), textCharFormat.foreground().color().blue());
                QColor textColor(textCharFormat.foreground().color().name(QColor::HexRgb));
                QString sname = textColor.name(QColor::HexRgb);


               QTextCharFormat format;
               format.setFont(font);
               format.setForeground(textColor);

               QTextCursor prev_cursor = ui.textBrowser->textCursor();
               //ui.textBrowser->textCursor().beginEditBlock();
               ui.textBrowser->moveCursor(QTextCursor::End);
              // ui.textBrowser->textCursor().movePosition(QTextCursor::End);
               ui.textBrowser->textCursor().insertText(currentFragment.text(), format);
              //  ui.textBrowser->textCursor().insertText("\n", format);
              // ui.textBrowser->append(currentFragment.text());
              // ui.textBrowser->textCursor().endEditBlock();
                ui.textBrowser->setTextCursor(prev_cursor);


           }
           //int j = 0;
        }

        ui.textBrowser->textCursor().insertBlock();
    }
 qDebug() << ui.textEdit->textCursor().selectedText();
    ui.textEdit->clear();
    ui.textEdit->setFocus();
}

void Chat::setUserPortrait(QPixmap pixmap)
{
    if (pixmap.isNull())
        pixmap = QPixmap(":/Resources/UserFace/face.jpg");

    if (pixmap.size() != QSize())
    {
        QPixmap mask(pixmap.size());
        QPainter maskPainter(&mask);
        maskPainter.fillRect(mask.rect(), Qt::white);
        maskPainter.setBrush(Qt::black);
        maskPainter.drawRoundedRect(mask.rect(), 10, 10);
        pixmap.setMask(mask.createMaskFromColor(Qt::white));
        ui.portraitLabel->setPixmap(pixmap);
    }
}
